import { InjectRepository } from '@nestjs/typeorm';
import { RoleEntity } from './entity/role.entity';
import { InsertResult, Repository, UpdateResult } from 'typeorm';
import { AddRoleDto } from './dto/addRoleDto';
import { EditRoleDto } from './dto/editRoleDto';

export class TestRepository {

  constructor(@InjectRepository(RoleEntity) private testRepository: Repository<RoleEntity>) { }

  /**
   * 新增
   * @param addRoleDto 角色数据
   * @returns true or false
   */
  addRole(addRoleDto: AddRoleDto): Promise<InsertResult> {
    return this.testRepository
      .createQueryBuilder()
      .insert()
      .into(RoleEntity)
      .values([
        {
          role_name: addRoleDto.roleName,
          role_code: addRoleDto.roleCode,
          create_user_id: 1
        }
      ])
      .execute()
  }

  /**
   * 查询
   * @param id 角色Id
   * @returns 角色信息
   */
  getRole(id: number): Promise<RoleEntity | null> {
    return this.testRepository.findOne({
      where: { delete_flag: false, id }
    })
  }

  /**
   * 编辑
   * @param editRoleDto 数据信息
   * @returns true or false 
   */
  editRole(editRoleDto: EditRoleDto): Promise<UpdateResult> {
    return this.testRepository
      .createQueryBuilder()
      .update(RoleEntity)
      .set({ role_name: editRoleDto.roleName })
      .where("deleted_flag = false")
      .where("id = :id", { id: editRoleDto.id })
      .execute()
  }

  /**
   * 删除
   * @param id 角色ID
   * @returns true or false
   */
  deleteRole(id: number): Promise<UpdateResult> {
    return this.testRepository
      .createQueryBuilder()
      .update(RoleEntity)
      .set({ delete_flag: true })
      .where("id = :id", { id })
      .execute()
  }
} 